package com.xjt.wx_admin.service.impl;

import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjt.wx_admin.entity.MsgRecord;
import com.xjt.wx_admin.entity.dto.SendMsg;
import com.xjt.wx_admin.mapper.MsgRecordMapper;
import com.xjt.wx_admin.service.MsgRecordService;
import com.xjt.wx_admin.service.UserLatelyMsgService;
import com.xjt.wx_admin.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Xujt
 * @since 2023-03-22 11:33:28
 */
@Service
public class MsgRecordServiceImpl extends ServiceImpl<MsgRecordMapper, MsgRecord> implements MsgRecordService {


    @Autowired
    UserLatelyMsgService userLatelyMsgService;

    public Page<MsgRecord> queryUserMsg(Page page, Long toId){
        Long userId = SecurityUtils.getUserId();
        Page<MsgRecord> msgRecords = baseMapper.queryUserMsg(page,userId, toId);
        List<MsgRecord> records = msgRecords.getRecords();
        for (MsgRecord record : records) {
            if (record.getRemark()!=null && !record.getRemark().equals("")){
                record.setFriendName(record.getRemark());
            }
        }
        Collections.reverse(records);
        return msgRecords;
    }

    @Override
    public R sendMsg(SendMsg sendMsg) {
        MsgRecord msgRecord = new MsgRecord();
        msgRecord.setMsg(sendMsg.getMsg());
        msgRecord.setMsgType(sendMsg.getType());
        msgRecord.setSendTime(LocalDateTime.now());
        msgRecord.setFromId(SecurityUtils.getUserId());
        msgRecord.setToId(sendMsg.getToId());
//        更新会话信息
        userLatelyMsgService.updateSessionMsg(sendMsg);
        return R.ok(save(msgRecord));
    }
}
